#include "LoadDB.h"
#include "ui_LoadDB.h"
#include <QDesktopWidget>



LoadDB::LoadDB(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoadDB)
{
    ui->setupUi(this);

    auto desktop = SystemVal::GetInstance()->desktop;
    move((desktop->width()-this->width())/2,(desktop->height()-this->height())/2);
}

LoadDB::~LoadDB()
{
    delete ui;
}


void LoadDB::on_pb_Next_clicked()
{
    if(equal){
        QMessageBox::warning(nullptr,"警告","目标数据库和对象数据库相同!");
        return;
    }
    if(ori_OK && ori_OK){
        emit openMain();
    }else{
        QMessageBox::warning(nullptr,"警告","请加载数据库!");
    }
}

void LoadDB::on_pb_openTarget_clicked()
{
    QString file_name = QFileDialog::getOpenFileName(this,"打开SQLite3",".","*.db");
    QString Name=file_name.section('/', -1);


    auto & dbtf = SystemVal::GetInstance()->writes;
    if(last_tar.isEmpty()){
        dbtf = QSqlDatabase::addDatabase("QSQLITE","TAR");
    }else{
        dbtf.close();
    }
    dbtf.setDatabaseName(file_name);
    if(!dbtf.open()){
        dbtf.close();
        // dbtf.removeDatabase("TAR");
        QLOG_LINE << "打开数据库失败";
        tar_OK = false;
        return ;
    }else{
        QLOG_LINE << "打开数据库成功";
        tar_OK = true;
        last_tar = file_name;
    }
    auto asf = SystemVal::GetInstance()->old_Data;

    if(last_ori == last_tar && (!last_ori.isEmpty()) && (!last_tar.isEmpty())){
        equal = true;
    }else{
        equal = false;
    }

    ui->lb_tar_name->setText(Name);
    ui->lb_tar_path->setText(file_name.left(file_name.lastIndexOf("/")));
}




//! 将转换为应用
void LoadDB::convert(PAR_VAL &rd, DBValue &pr,QString type)
{
    if(rd[type].empty()){
        QLOG_LINE << type << " 为空!";
    }else{
        QList<int> seamids;
        seamids = rd[type].keys();

        QStringList list;
        if("SEAMINFO" == type){
            list = SystemVal::GetInstance()->dbTables;
        }else{
            list.append("CAD");
        }
        for(auto t:seamids){    //! 遍历所有的seamid
            for(auto s:list){   //! 编译所有的表名
                pr[t][s]=(rd[s][t]);
            }
        }
    }
}

// 打开原始的数据库
void LoadDB::on_pb_openOri_clicked()
{
    QString file_name = QFileDialog::getOpenFileName(this,"打开SQLite3",".","*.db");

    QString Name=file_name.section('/', -1);


    if(last_ori.isEmpty()){
         dbT1 = QSqlDatabase::addDatabase("QSQLITE","ORI");
    }

    dbT1.setDatabaseName(file_name);
    if(!dbT1.open()){
        dbT1.close();
        dbT1.removeDatabase("ORI");
        QLOG_LINE << "打开数据库失败";
        ori_OK = false;
        return;
    }else{
        QLOG_LINE << "打开数据库成功";
        ori_OK = true;
        last_ori = file_name;
    }

    auto pr = parseOri(SystemVal::GetInstance()->dbTables);
    QStringList cadls;
    cadls.append("CAD");
    auto cads = parseOri(cadls,"CADCODE");
    convert(pr,SystemVal::GetInstance()->old_Data);
    convert(cads,SystemVal::GetInstance()->cad_Data,"CAD");
    if(last_ori == last_tar && (!last_ori.isEmpty()) && (!last_tar.isEmpty())){
        equal = true;
    }else{
        equal = false;
    }

    ui->lb_ori_name->setText(Name);
    ui->lb_ori_path->setText(file_name.left(file_name.lastIndexOf("/")));
}


PAR_VAL LoadDB::parseOri(QStringList list,QString zd)
{
    QSqlQuery query(dbT1);
    QString selectTabl_Data = "SELECT * FROM %1 ";
    QString keys = "PRAGMA table_info('%1')";
    PAR_VAL a_id_pack;    //! 所有的表数据
    for (QString t:list) {
        QStringList t_key;  //! 该表的所有字段
        QString key_t = keys.arg(t);
        query.exec(key_t);
        while (query.next())
        {
//            QLOG_LINE << "序号:" << query.value(0).toString();
//            QLOG_LINE << "字段:" << query.value(1).toString();
//            QLOG_LINE << "类型:" << query.value(2).toString();
            t_key.push_back(query.value(1).toString());
        }

        TableValue t_vals;
        QString sqd;
        if(t_key.contains("ENABLED")){
            sqd =  selectTabl_Data.arg(t);
            sqd += " WHERE ENABLED=1";
        }else{
            sqd =  selectTabl_Data.arg(t);
        }

        query.exec(sqd);

        // QLOG_LINE<<sqd;
        ID_VAL tval;
        MULT_ROW mrow;  //!该表的多行数据
        //! 获取该表的所有ID们的整行数据
        while (query.next())
        {
            ROW_DATA row;
            //! 这里解析了一行的数据
            for(auto key:t_key){
                row[key] = query.value(key).toString();
            }
            mrow.push_back(row);
        }
        QList<int> fadada12 ;
        for(auto it : mrow){
            // tval[it["SEAMID"].toUInt()] = mrow;
            fadada12.push_back(it[zd].toUInt());
        }
        QSet<int>fsdff12 ( fadada12.begin(),fadada12.end() );
        fadada12 = fsdff12.values();
        std::sort(fadada12.begin(),fadada12.end());

        for(int m_id:fadada12){
            MULT_ROW id_row;
            for(auto it : mrow){
                // tval[it["SEAMID"].toUInt()] = mrow;
                // fadada12.push_back(it["SEAMID"].toUInt());
                if(it[zd].toUInt() == (uint)m_id){
                    id_row.push_back(it);
                }else{
                    continue;
                }
            }
            tval[m_id] = id_row;
        }

         a_id_pack[t] = tval;
    }
    return a_id_pack;
}
